package com.sz.jinzheng.controller;

import com.sz.jinzheng.mapper.BorrowInfoMapper;
import com.sz.jinzheng.model.BillForm;
import com.sz.jinzheng.model.Interest;
import com.sz.jinzheng.model.Result;
import com.sz.jinzheng.service.BillFormService;
import com.sz.jinzheng.service.BorrowInfoService;
import com.sz.jinzheng.service.TbillFormService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Timestamp;


@RestController
@RequestMapping("/user")
@Slf4j
public class BillFormController {
    @Autowired
    private BillFormService billFormService;
    @Autowired
    private BorrowInfoService borrowInfoService;
    @Autowired
    private TbillFormService tbillFormService;

    /**
     * 查询账单(当月)
     *
     * @param token
     * @return
     */
    @PostMapping("/getbBillForm")
    public Result getbBillForm(String token, Integer borrowerInfoId) {
        //先查询当前日期与账单生成时间相比看看是第几期
        int borrowInfoId = borrowInfoService.getborrowInfoid(borrowerInfoId);
        System.out.println("borrowInfoId = " + borrowInfoId);
        Interest interest = tbillFormService.getInterest(borrowInfoId);//通过用户id调用interest方法查询
        Timestamp createTime = interest.getCreateTime();//获得用户借款时间(该方法可以将数据库的时间戳转换为java的)
        long time = createTime.getTime();//创建时间转换long；
        long e = System.currentTimeMillis();//获取现在时间
        // 下面这个方法不严谨，应该用向上取整
        int whichIssue = Math.toIntExact((e - time) / ((long) 1000 * (long) 24 * (long) 3600 * (long) 30)) + 1;//第几期
        //查询到当前
        System.out.println("whichIssue = " + whichIssue);
        BillForm billForms = billFormService.getOneBillForm(new BillForm(borrowInfoId, whichIssue));
        //获取一共多少期
        int count = billFormService.getCount(borrowInfoId).size();
        if (billForms == null) {
            return new Result(444, "获取账单失败！", "系统内部错误！");
        }
        billForms = billFormService.latePayment(billForms);//得到罚息金额和天数
        System.out.println("endTime = " + billForms.getEndTime());
        return new Result(200, "获取账单成功！", billForms, Integer.toString(count));

    }


    /**
     * 查询账单(第N期)
     *
     * @param
     * @param billForm1 封装的贷款id和第几期信息
     * @return
     */
    @PostMapping("/getOneBillForm")
    public Result getOneBillForm(@RequestBody BillForm billForm1) {
        System.out.println(billForm1.getWhichIssue());
        System.out.println(billForm1.getBorrowInfoId());
        BillForm billForms = billFormService.getOneBillForm(billForm1);
        return new Result(200, "获取账单成功！", billForms);

    }
}
